//
//  STDataViewModel.swift
//  Demo-04-TabBarTest
//
//  Created by 苏统世 on 16/5/15.
//  Copyright © 2016年 SuTon. All rights reserved.
//

import UIKit

class STDataViewModel: NSObject {

    static let shareManager:STDataViewModel=STDataViewModel()
    
    // MARK: - 加载微博信息
    func loadMessages(since_id: Int64, max_id: Int64,callBackDatas:(datas:[STData])->()){
        guard let access_token=STUserAccountViewModel.shareManager.userAccount?.access_token else{ return }
        
        let messagesURL = "2/statuses/home_timeline.json"
        
        // 参数
        var parameters: [String: AnyObject] = [
            "access_token" : access_token
        ]
        if since_id > 0 {
            // 别人传了 since_id,拼接since_id
            parameters["since_id"] = NSNumber(longLong: since_id)
        } else if max_id > 0 {
            // 别人传了 max_id,拼接max_id
            parameters["max_id"] = NSNumber(longLong: max_id)
        }
        
        STNetworkTool.netManager.request(RequestMethod.GET, URLString: messagesURL, parameters: parameters, success: { (_, responsedData) -> Void in
            
//            STPrint(items: "成功获取微博数据=====>：\(responsedData)")
            if let result = responsedData as? [String: AnyObject] {
                if let statuses = result["statuses"] as? [[String:AnyObject]]{
                
                    var dataArray = [STData]()
                    for dict in statuses{
                        dataArray.append(STData.init(dict: dict))
                    }
                    callBackDatas(datas: dataArray)
                }
            }
            }) { (_, error) -> Void in
                STPrint(items: "无法获取微博数据")
        }
    }
    /// 发送微博信息
    func sendMessage(status: String,sendCallBackBlock: (error:NSError?)->()){
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        guard let access_token=STUserAccountViewModel.shareManager.userAccount?.access_token else{ return }
        // 请求参数
        let parameters: [String: AnyObject] = [
            "access_token" : access_token,
            "status" : status
        ]
        STNetworkTool.netManager.request(RequestMethod.POST, URLString: urlString, parameters: parameters, success: { (_, respondData) -> Void in
            STPrint(items: "发布成功")
            sendCallBackBlock(error: nil)
            }) { (_, error) -> Void in
                STPrint(items: "发布失败")
                sendCallBackBlock(error: error)
        }
        
    }
}
